<template>
  <div class="plain-text-editor">
    <div class="editor-toolbar">
      <div class="toolbar-left">
        <el-button size="small" @click="clearEditor">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        <el-button size="small" @click="insertTemplate">
          <el-icon><Plus /></el-icon>
          模板
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-tag type="success" size="small">纯文本编辑器</el-tag>
      </div>
    </div>
    
    <div class="editor-container">
      <!-- 使用原生textarea，避免Vue的响应式开销 -->
      <textarea
        ref="textareaRef"
        class="plain-textarea"
        :placeholder="placeholder"
        :rows="rows"
        @input="handleInput"
        @keydown="handleKeydown"
      ></textarea>
    </div>
    
    <div class="editor-footer">
      <div class="footer-left">
        <span class="editor-info">字符数: {{ characterCount }}</span>
        <span class="editor-info">行数: {{ lineCount }}</span>
      </div>
      <div class="footer-right">
        <el-button 
          type="primary" 
          size="small" 
          @click="executeSQL"
          :loading="executing"
          :disabled="!hasContent || !selectedDatabase"
        >
          <el-icon><CaretRight /></el-icon>
          执行 (Ctrl+Enter)
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus, CaretRight } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: { type: String, default: '' },
  selectedDatabase: { type: [String, Number], default: null },
  executing: { type: Boolean, default: false },
  placeholder: { type: String, default: '请输入SQL查询语句...' },
  rows: { type: Number, default: 20 }
})

// Emits
const emit = defineEmits(['update:modelValue', 'execute'])

// 响应式数据
const textareaRef = ref(null)
const characterCount = ref(0)
const lineCount = ref(1)
const hasContent = ref(false)

// 避免使用Vue的响应式v-model，直接操作DOM
let currentValue = props.modelValue || ''

// 极简的输入处理（无防抖，直接处理）
const handleInput = (event) => {
  try {
    currentValue = event.target.value
    characterCount.value = currentValue.length
    lineCount.value = currentValue.split('\n').length
    hasContent.value = currentValue.trim().length > 0
    
    // 直接emit，不使用防抖
    emit('update:modelValue', currentValue)
  } catch (error) {
    console.error('PlainTextEditor: 输入处理错误:', error)
  }
}

// 键盘事件处理
const handleKeydown = (event) => {
  try {
    // Ctrl+Enter 执行SQL
    if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
      event.preventDefault()
      executeSQL()
      return
    }
    
    // Tab键插入空格
    if (event.key === 'Tab') {
      event.preventDefault()
      const textarea = event.target
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      
      // 插入4个空格
      const spaces = '    '
      textarea.value = textarea.value.substring(0, start) + spaces + textarea.value.substring(end)
      textarea.selectionStart = textarea.selectionEnd = start + spaces.length
      
      // 触发input事件
      handleInput({ target: textarea })
    }
  } catch (error) {
    console.error('PlainTextEditor: 键盘事件处理错误:', error)
  }
}

// 清空编辑器
const clearEditor = () => {
  try {
    if (textareaRef.value) {
      textareaRef.value.value = ''
      currentValue = ''
      characterCount.value = 0
      lineCount.value = 1
      hasContent.value = false
      emit('update:modelValue', '')
      textareaRef.value.focus()
    }
  } catch (error) {
    console.error('PlainTextEditor: 清空失败:', error)
  }
}

// 插入SQL模板
const insertTemplate = () => {
  try {
    const template = 'SELECT * FROM table_name WHERE condition;'
    if (textareaRef.value) {
      const textarea = textareaRef.value
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      
      const newValue = textarea.value.substring(0, start) + template + textarea.value.substring(end)
      textarea.value = newValue
      textarea.selectionStart = textarea.selectionEnd = start + template.length
      
      // 更新状态
      currentValue = newValue
      characterCount.value = newValue.length
      lineCount.value = newValue.split('\n').length
      hasContent.value = newValue.trim().length > 0
      emit('update:modelValue', newValue)
      
      textarea.focus()
    }
  } catch (error) {
    console.error('PlainTextEditor: 插入模板失败:', error)
  }
}

// 执行SQL
const executeSQL = () => {
  try {
    if (!hasContent.value) {
      ElMessage.warning('请输入SQL语句')
      return
    }
    
    if (!props.selectedDatabase) {
      ElMessage.warning('请选择数据库')
      return
    }
    
    emit('execute', currentValue)
  } catch (error) {
    console.error('PlainTextEditor: 执行SQL失败:', error)
  }
}

// 监听props变化（简化版本）
watch(() => props.modelValue, (newValue) => {
  if (newValue !== currentValue && textareaRef.value) {
    try {
      textareaRef.value.value = newValue || ''
      currentValue = newValue || ''
      characterCount.value = currentValue.length
      lineCount.value = currentValue.split('\n').length
      hasContent.value = currentValue.trim().length > 0
    } catch (error) {
      console.error('PlainTextEditor: 设置值失败:', error)
    }
  }
})

// 组件挂载
onMounted(() => {
  try {
    console.log('PlainTextEditor: 组件挂载')
    
    nextTick(() => {
      if (textareaRef.value) {
        // 设置初始值
        textareaRef.value.value = currentValue
        characterCount.value = currentValue.length
        lineCount.value = currentValue.split('\n').length
        hasContent.value = currentValue.trim().length > 0
        
        // 聚焦到编辑器
        textareaRef.value.focus()
      }
    })
  } catch (error) {
    console.error('PlainTextEditor: 挂载失败:', error)
  }
})

// 组件卸载
onBeforeUnmount(() => {
  try {
    console.log('PlainTextEditor: 组件卸载')
    // 清理引用
    textareaRef.value = null
  } catch (error) {
    console.error('PlainTextEditor: 卸载失败:', error)
  }
})

// 暴露方法
defineExpose({
  clearEditor,
  insertTemplate,
  focus: () => {
    try {
      if (textareaRef.value) {
        textareaRef.value.focus()
      }
    } catch (error) {
      console.error('PlainTextEditor: 聚焦失败:', error)
    }
  },
  setValue: (value) => {
    try {
      if (textareaRef.value) {
        textareaRef.value.value = value || ''
        currentValue = value || ''
        characterCount.value = currentValue.length
        lineCount.value = currentValue.split('\n').length
        hasContent.value = currentValue.trim().length > 0
        emit('update:modelValue', currentValue)
      }
    } catch (error) {
      console.error('PlainTextEditor: 设置值失败:', error)
    }
  },
  getValue: () => currentValue,
  isReady: () => !!textareaRef.value
})
</script>

<style scoped>
.plain-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor-container {
  position: relative;
}

.plain-textarea {
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  padding: 12px;
  font-family: 'Courier New', Consolas, Monaco, monospace;
  font-size: 14px;
  line-height: 1.5;
  background: #fafafa;
  color: #333;
  box-sizing: border-box;
}

.plain-textarea:focus {
  background: #fff;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  background: #f5f7fa;
  border-top: 1px solid #dcdfe6;
  font-size: 12px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-right {
  display: flex;
  align-items: center;
}

.editor-info {
  color: #909399;
}
</style>
